from flask import Blueprint, render_template, request, redirect, session
from utils import db, response  # 导入数据库查询函数

# 蓝图对象
ac = Blueprint("account", __name__)

@ac.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html") 
        # 渲染登录页面 将Python变量注入HTML模板，自动在templates目录查找模板文件

    role = request.form.get("role")
    mobile = request.form.get("mobile")
    password = request.form.get("password")
    print(role, mobile, password)

    # 连接MySQL并执行SQL语句查询用户密码是否正确
    #result 默认返回元组，所以我们要想办法让它返回的是字典
    result =  db.fetch_one("SELECT * FROM user_info WHERE mobile=%s AND password=%s AND role=%s",
              (mobile, password, role))

    print(result)

    if result:
        #登录成功＋跳转
        session['user_info'] = {'role': result['role'], 'real_name': result['real_name'], 'id': result['id']} #登录凭证
        return redirect('/order/list')#重定向到新URL
    
    else:
        return render_template("login.html", error = "用户名或密码错误")

    # 去数据库验证
    return "ok"


@ac.route("/api/users", methods=["GET", "POST"])
def users():
    '''创建用户'''
    title = request.json.get("title")
    content = request.json.get("content")
    mood = request.json.get("mood")
    weather = request.json.get("weather")
    tags = request.json.get("tags")
    is_public = request.json.get("is_public")
    db.insert("insert into `writer` (title,content,mood,weather,tags,is_public) values(%s, %s, %s, %s, %s, %s)",[title,content,mood,weather,tags,is_public])

    return response.res_200()

ac.route("/api/writer")
def writer_list():
    """获取所有的文章列表"""
    sql = "select * from writer "
    data = db.fetch_all(sql, [])
    return response.res_200(data=data)


